const { Readable } = require('stream');

const path = require('path');


function readBody(stream) {
    if (stream instanceof Readable) {
        return new Promise((resolve, reject) => {
            try {
                let res = '';
                stream
                    .on('data', (chunk) => res += chunk)
                    .on('end', () => resolve(res));
            } catch (error) {
                reject(error);
            }
        })
    } else {
        return stream.toString();
    }
}


function resolveVue(root) {
    const compilerPkgPath = path.resolve(root, 'node_modules', '@vue/compiler-sfc/package.json');
    const compilerPkg = require(compilerPkgPath);
    // 编译模块的路径 node 中编译
    const compilerPath = path.join(path.dirname(compilerPkgPath), compilerPkg.main);
    const resolvePath = (name) => path.resolve(root, 'node_modules', `@vue/${name}/dist/${name}.esm-bundler.js`);
    // dom 运行
    const runtimeDomPath = resolvePath('runtime-dom');
    // 核心运行
    const runtimeCorePath = resolvePath('runtime-core');
    // 响应式模块
    const reactivityPath = resolvePath('reactivity');
    // 共享模块
    const sharedPath = resolvePath('shared');
    return {
        vue: runtimeDomPath,
        '@vue/runtime-dom': runtimeDomPath,
        '@vue/runtime-core': runtimeCorePath,
        '@vue/reactivity': reactivityPath,
        '@vue/shared': sharedPath,
        compiler: compilerPath,
    }
}

exports.readBody = readBody;
exports.resolveVue = resolveVue;
